package com.shop.cloud.common.storage.util;

import com.shop.cloud.common.storage.entity.StorageConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @JL
 * minio
 * 各操作调用
 */
@AllArgsConstructor
public class MinioUtils {
	private final StorageConfig storageConfig;

	/**
	 * 上传文件
	 * @param file
	 * @param dir 用户上传文件时指定的文件夹。
	 */
	public String uploadFile(File file,String dir) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InternalException, ErrorResponseException, XmlParserException, ServerException, InvalidResponseException {
		MinioClient minioClient = MinioClient.builder().endpoint(storageConfig.getEndpoint())
				.credentials(storageConfig.getAccessKeyId(), storageConfig.getAccessKeySecret())
				.build();
		String fileName = file.getName();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		String key = dir + UUID.randomUUID()+ "." + suffix;
		String type = URLConnection.guessContentTypeFromName(file.getName());;
		PutObjectArgs putObjectArgs = PutObjectArgs.builder()
				.bucket(storageConfig.getBucket())
				.object(key)
				.stream(new FileInputStream(file), file.length(), -1)
				.contentType(type)
				.build();
		minioClient.putObject(putObjectArgs);
		String resultStr = storageConfig.getEndpoint()+storageConfig.getBucket()+"/"+key;
		return resultStr;
	}
}
